/*
 * Copyright 2018 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.scp.admin.config;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springmodules.validation.commons.DefaultBeanValidator;
import org.springmodules.validation.commons.DefaultValidatorFactory;
import org.springmodules.validation.commons.ValidatorFactory;

/**
 * <pre>
 *	统一配置一些要加载的类，比如：校验
 * </pre>
 * 
 * @author 劳水生 Exp
 * @Date 2018年1月17日 下午3:40:57
 * @since 1.0
 */
@Configuration
public class ValidateConfig {
	private Logger logger = LoggerFactory.getLogger(ValidateConfig.class);

	/**
	 * <pre>
	 * 验证框架工厂类初始化
	 * </pre>
	 * 
	 * @return
	 * @throws IOException
	 */
	@Bean("validatorFactory")
	public DefaultValidatorFactory getDefaultValidatorFactory() throws IOException {
		logger.info("加载了验证框架..");

		DefaultValidatorFactory dvf = new DefaultValidatorFactory();
		ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
		Resource[] resources = (Resource[]) resolver.getResources("classpath*:validate/*/*.xml");

		if (logger.isDebugEnabled()) {
			if (resources != null) {
				for (Resource res : resources) {
					logger.debug("加载验证文件,{}", res.getURI());
				}
			}
		}
		dvf.setValidationConfigLocations(resources);
		return dvf;

	}

	/**
	 * <pre>
	 * 验证服务接口
	 * </pre>
	 * 
	 * @param vf
	 * @return
	 */
	@Bean("validator")
	public DefaultBeanValidator getDefaultBeanValidator(@Qualifier("validatorFactory") ValidatorFactory vf) {
		DefaultBeanValidator dbValidator = new DefaultBeanValidator();
		dbValidator.setValidatorFactory(vf);
		return dbValidator;
	}

	/**
	 * <pre>
	 * 资源文件读取服务
	 * </pre>
	 * 
	 * @return
	 * @throws Exception
	 */
	@Bean("messageSource")
	public ResourceBundleMessageSource getMsg() throws Exception {
		ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
		rbms.setDefaultEncoding("UTF-8");
		rbms.setBasenames("alertMessage", "labelMessage");
		return rbms;
	}

}
